<template>
  <div class="app-container pmDetail">
    <el-descriptions title="基本信息" :column="2" border>
      <el-descriptions-item label="无人机id">{{ baseinfo.deviceId }}</el-descriptions-item>
      <el-descriptions-item label="对应街道">{{ baseinfo.jd }}</el-descriptions-item>
      <el-descriptions-item label="任务分区时间">{{ baseinfo.fq }}</el-descriptions-item>
    </el-descriptions>
    <el-descriptions class="margin-top-10" title="地图点位" border>
    </el-descriptions>
    <div>
      <el-form ref="form" :inline="true" :model="form" label-width="80px" >
        <el-row>
          <el-col :span="20"> 
            <el-form-item label="">
              <el-select v-model="showDataType" placeholder="请选择数据类型" @change="getPmListByFq">
                <el-option
                  v-for="dict in dict.type.sys_data_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div id="container"></div>
    <el-descriptions class="margin-top-10 pointEdit" title="点位编辑" border :column="2" v-if="editPointInfo.pm">
      <el-descriptions-item label="PM2.5">
        <div v-show="isEdit" style="display: inline-block;">
          <el-input style="width: 200px" v-model="editPointInfo.pm" placeholder="请输入pm"></el-input>
        </div>
        <span v-show="!isEdit">{{ editPointInfo.pm }}</span>
        <span class="isEdit" @click="editOriginalData">{{ isEdit ? '保存' : '编辑' }}</span>
      </el-descriptions-item>
      <el-descriptions-item label="NO2">
        <div v-show="isEdit" style="display: inline-block;">
          <el-input style="width: 200px" v-model="editPointInfo.no2" placeholder="请输入NO2"></el-input>
        </div>
        <span v-show="!isEdit">{{ editPointInfo.no2 }}</span>
        <span class="isEdit" @click="editOriginalData">{{ isEdit ? '保存' : '编辑' }}</span>
      </el-descriptions-item>
    </el-descriptions>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import { getPmListByFq, updateInfo,editOriginalData } from '@/api/wrj/info';
export default {
  name: 'pmDetail',
  dicts: ['sys_jd_name','sys_data_type'],
  data() {
    return {
      baseinfo: {},
      map: null,
      polygonArr: [],
      // pm2.5区块矩形数组对象，有颜色，
      pmPolygonArr:[],
      pm25List: [],
      editPointInfo: {},
      isEdit: false,
      textArr: [],
      textFontSize:10,
      showDataType:'PM2.5(ug/m3)',
    }
  },
  mounted() {
    if(this.$route.query.jd) {
      this.getPmListByFq()
    }
  },
  methods: {
    getPmListByFq() {
      getPmListByFq({
        jd: this.$route.query.jd,
        fq: this.$route.query.fq
      }).then(res => {
        console.log(res)
        if(res.pmList.length > 0) {
          this.baseinfo = res.pmList[0];
          this.pm25List = res.pmList;
          this.initAMap();
        }
      })
    },
    initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "ea203d3756bb886bcdd4833c10c332b9",
      };
      AMapLoader.load({
        key: "475db83acfc1af0cbab24fbdaa34072c", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
        .then((AMap) => {
          this.defaultLayer = new AMap.createDefaultLayer()
          this.satelliteLayer = new AMap.TileLayer.Satellite();
          this.map = new AMap.Map("container", {
            // 设置地图容器id
            viewMode: "3D", // 是否为3D地图模式
            zoom: 15, // 初始化地图级别
            center: [120.577490, 29.932739], // 初始化地图中心点位置
            layers: [this.satelliteLayer],
          });
          this.drawPmRectangleAndText();
          // 地图缩放监听事件
          this.map.on('zoomend', this.mapZoomend);
        })
        .catch((e) => {
          console.log(e);
        });
    },
    //地图缩放结束后的方法
    mapZoomend(){
      var zoom = this.map.getZoom();
      if(zoom<=16){
        this.textFontSize=14;
        this.drawPmRectangleAndText()
      }else if(zoom>16 && zoom<=17){
        this.textFontSize=18;
        this.drawPmRectangleAndText()
      }else if(zoom>17 && zoom<=18){
        this.textFontSize=26;
        this.drawPmRectangleAndText()
      }else if(zoom>18){
        this.textFontSize=32;
        this.drawPmRectangleAndText()
      }
      // console.log("地图等级：",zoom)
    },
    //画pm2.5的数值以及文字
    drawPmRectangleAndText(){
      this.map.remove(this.pmPolygonArr);
      this.map.remove(this.textArr);
      this.pmPolygonArr=[];
      this.textArr=[];
      this.pm25List.forEach(element => {
        var southWest = new AMap.LngLat(element.minLng, element.maxLat)
        var northEast = new AMap.LngLat(element.maxLng, element.minLat)

        var bounds = new AMap.Bounds(southWest, northEast)

        var color = this.getColor(element.messageInfo.airData[this.showDataType]);

        // console.log(color)
        let rectangle = new AMap.Rectangle({
            title: element.id,
            bounds: bounds,
            strokeColor:color,
            strokeWeight: 1,
            strokeOpacity:0.5,
            strokeDasharray: [30,10],
            // strokeStyle还支持 solid
            strokeStyle: 'dashed',
            // fillColor:'rgb(0,0,0)',
            fillColor:color,
            fillOpacity:0.7,
            cursor:'pointer',
            zIndex:50,
            extData: {
              id: element.id,
              jd: element.jd,
              fq: element.fq,
              pm: element.messageInfo.airData['PM2.5(ug/m3)'],
              no2: element.messageInfo.airData['NO2(ppm)'],
            }
        })

        let text = new AMap.Text({
          text: element.messageInfo.airData[this.showDataType],
          anchor:'center',
          position: rectangle.getBounds().getCenter(), // 文字位置
          style: {
            // 'padding': '.75rem 1.25rem',
            // 'margin-bottom': '1rem',
            'border-radius': '.25rem',
            'background-color': 'rgba(255,255,255,0)',
            // 'width': '15rem',
            'border-width': 0,
            'text-align': 'center',
            'font-size': this.textFontSize+'px',
            'color': 'white'
          },
          extData: {
            id: element.id,
            jd: element.jd,
            fq: element.fq,
            pm: element.messageInfo.airData['PM2.5(ug/m3)'],
            no2: element.messageInfo.airData['NO2(ppm)'],
          }
        });
        this.textArr.push(text);
        this.pmPolygonArr.push(rectangle);

        rectangle.on('click', this.pointClick)
        text.on('click', this.pointClick)
      });
      if(this.pmPolygonArr.length>0){
        console.log("dal")
        this.map.add(this.pmPolygonArr);
        this.map.add(this.textArr);
        // this.map.setFitView(this.pmPolygonArr)
      }
    },

    getColor(color){
      if(color>=0 && color<=35){
        return "rgb(53 ,172 ,10)"
      }else if(color>35 && color<=75){
        return "rgb(222, 217 ,7)"
      }else if(color>75 && color<=115){
        return "rgb(242 ,166, 48)"
      }else if(color>115 && color<=150){
        return "rgb(241, 15 ,15)"
      }else if(color>150 ){
        return "rgb(75, 0, 149)"
      }
    },

    pointClick(e) {
      // console.log(e)
      var extraData = e.target.getExtData();
      console.log('Extra Data:', extraData);
      this.isEdit = true;
      this.editPointInfo = extraData;
    },

    editOriginalData() {
      this.isEdit = !this.isEdit;
      if(!this.editPointInfo.id) {
        this.$message.info('请选择具体点位!')
      } else if(!this.isEdit) {
        editOriginalData(this.editPointInfo).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.editPointInfo = {};
          this.isEdit = false;
          this.getPmListByFq()
        });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.pmDetail {
  width: 100%;
  #container {
    width: 100%;
    height: 500px;
  }
  .isEdit {
    color: rgb(64, 158, 255);
    margin-left: 20px;
    font-size: 14px;
  }
  .margin-top-10 {
    margin-top: 10px;
  }
}
</style>

<style>
.pointEdit /deep/ .el-descriptions-item__label {
  width: 50% !important;
}

.pointEdit .el-descriptions__label {
  width: 50%; /* 设置您想要的宽度 */
  text-align: left; /* 根据需要设置对齐方式 */
}
</style>